package p13.code;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;

public class LifeCycleWebServer {

    // 创建一个限制最大数量的线程池
    private final ExecutorService exec = Executors.newFixedThreadPool(100);

    public void start() throws IOException {

        ServerSocket socket = new ServerSocket(80);

        //如果线程池没有关闭，则接受任务
        while(!exec.isShutdown()) {
            try{
                final Socket conn = socket.accept();
                exec.execute(new Runnable(){
                    public void run(){
                        handleRequest(conn);
                    }
                });
            }catch(RejectedExecutionException e){
                if(!exec.isShutdown())
                    System.out.println("task submission rejected "+e);
            }
        }
    }

    //关闭服务
    public void stop() {
        exec.shutdown();
    }

    void handleRequest(Socket connection){
        System.out.println("这里处理请求");
    }


}
